/*
 * File:   main.c
 * Author:  Dominik H�ussler
 *          Ruben Schwarz
 *
 * Created on 2. M�rz 2011, 09:30
 *
 * �nderungen:
 * 2011/03/02   Real-Time-Clock implementiert
 *              UART2 f�r DEBUG-Zwecke implementiert
 */

#include "p33Fxxxx.h"
#include "FSIO.h"
#include <uart.h>
#include <stdlib.h>
#include "sensor_typedefs.h"
#include "communication.h"
#include "hardware_settings.h"
#include "logging.h"

// Select Internal FRC at POR
_FOSCSEL(FNOSC_FRC);

_FOSC(FCKSM_CSECMD & OSCIOFNC_OFF  & POSCMD_XT);	// Clock Switching is enabled and Fail Safe Clock Monitor is disabled
													// OSC2 Pin Function: OSC2 is Clock Output
													// Primary Oscillator Mode: XT Crystal

_FWDT(FWDTEN_OFF); // Watchdog Timer Enabled/disabled by user software


// Globale Variablen
ESystemState g_state = LOGGING_MODE;

void __attribute__((__interrupt__, auto_psv)) _T2Interrupt(void) {
    IEC0bits.T2IE = 0;
    char input = getcUART1();

    if (!DataRdyUART1()) {
        switch (input) {
            case GOTO_CONFIG_MODE: 	//TODO: auf Steuersignale reagieren (0x5A - Rücksetzen z.B.)
            	g_state = CONFIGURATION_MODE;
            default:
            	logData(input);
            	break;
        }
    }
    //Unbenoetigte Zeichen aus UART-Lesepuffer löschen
    while (DataRdyUART1()) getcUART1();
    IFS0bits.T2IF = 0; //Clear Timer Interrupt Flag
} //ISR Timer2

void __attribute__((__interrupt__, auto_psv)) _U1RXInterrupt(void) {
    //reset timer2 and enable interrupt
    TMR2 = 0;
    IFS0bits.T2IF = 0;
    IEC0bits.T2IE = 1;
    //T2CONbits.TON = 1;
    IFS0bits.U1RXIF = 0; //Flag löschen
}

int main(void) {
		//Init Peripherie
		//initClock(); enthaelt die alten clocksettings
		initUart();
		initTimer();
		initRemappablePins();
		//initChangeNotification();

    //Loop forever
    while (1) {

    	switch(g_state)
    	{
				case LOGGING_MODE:
				{
				}
				case CONFIGURATION_MODE:
				{
					//send "Ready for Configuration"

					//waiting for new configuration data

					//send "new config accepted"
				}
				case FAILSAFE_MODE:
				{
					//safe shutdown - reset?
				}
    	}


    }

    return 0;
}
